package com.youlai.boot.form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.form.mapper.FormDefinitionMapper;
import com.youlai.boot.form.service.FormDefinitionService;
import com.youlai.boot.form.model.entity.FormDefinition;
import com.youlai.boot.form.model.form.FormDefinitionForm;
import com.youlai.boot.form.model.query.FormDefinitionQuery;
import com.youlai.boot.form.model.vo.FormDefinitionVO;
import com.youlai.boot.form.converter.FormDefinitionConverter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 动态单定义服务实现类
 *
 * @author rabit
 * @since 2025-10-27 16:47
 */
@Service
@RequiredArgsConstructor
public class FormDefinitionServiceImpl extends ServiceImpl<FormDefinitionMapper, FormDefinition> implements FormDefinitionService {

    private final FormDefinitionConverter formDefinitionConverter;


    /**
     * 获取动态单定义分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<FormDefinitionVO>} 动态单定义分页列表
     */
    @Override
    public IPage<FormDefinitionVO> getFormDefinitionPage(FormDefinitionQuery queryParams) {
        return this.baseMapper.getFormDefinitionPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
    }

    /**
     * 获取动态单定义表单数据
     *
     * @param id 动态单定义ID
     * @return 动态单定义表单数据
     */
    @Override
    public FormDefinitionVO getFormDefinitionFormData(Long id) {
        FormDefinition entity = this.getById(id);
        return formDefinitionConverter.toVO(entity);
    }

    /**
     * 更新表单定义（自动备份旧版本并递增版本号）
     * 此逻辑保证新增和修改逻辑
     *
     * @param formData 动态单定义表单对象
     * @return 是否新增成功
     */
    @Override
    public Long saveOrUpdateFormDefinition(FormDefinitionForm formData) {
        FormDefinition entity = formDefinitionConverter.toEntity(formData);
        return updateFormDefinition(entity);
    }

    @Override
    public Long updateFormDefinition(FormDefinition entity) {
        //todo 此处需要增加日志记录

        //getFormCode 唯一，只能唯一标识，不唯一则更新
        FormDefinition currentForm = null;
        if (Objects.nonNull(entity.getId())){
           currentForm  = this.getById(entity.getId());
           entity.setId(null);
        }else {
            currentForm = this.baseMapper.selectOne(new QueryWrapper<FormDefinition>().lambda().eq(FormDefinition::getFormCode, entity.getFormCode()).eq(FormDefinition::getActive, 0), true);
        }

        if (Objects.nonNull(currentForm)) {
            if (!currentForm.getStatus().equals(0)) {
                //表单状态为异常状态，不允许修改数据
                throw new IllegalArgumentException("表单为停用状态，不允许修改数据");
            }

            //将该code 下的表单最大版本号递增
            int newVersion = currentForm.getMaxVersion() + 1;
            this.update(new UpdateWrapper<FormDefinition>().lambda().eq(FormDefinition::getFormCode, currentForm.getFormCode()).set(FormDefinition::getActive, 1).set(FormDefinition::getMaxVersion, newVersion).set(FormDefinition::getStatus, 2));

            entity.setVersion(newVersion);
            entity.setMaxVersion(newVersion);
            entity.setParentFormId(currentForm.getId());
            entity.setVersionHistory(handleNumberSequence(currentForm.getVersionHistory(), entity.getVersion()));
        } else {
            //表单不存在，执行新增逻辑
            int newVersion = 1;
            entity.setVersion(newVersion);
            entity.setMaxVersion(newVersion);
            entity.setVersionHistory(handleNumberSequence(null, newVersion));
            //执行新增逻辑
        }

        this.save(entity);
        return entity.getId();
    }



    /**
     * 删除动态单定义
     *
     * @param ids 动态单定义ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteFormDefinitions(String ids) {
        //todo 此处需要增加日志记录  还需要删除历史版本
        Assert.isTrue(StringUtils.isNotBlank(ids), "删除的动态单定义数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return removeByIds(idList);
    }

    @Override
    public boolean updateFormDefinitionStatus(Long id, Integer status) {
        //todo 此处需要增加日志记录
        //status 只允许 0 和 1
        FormDefinition entity = this.getById(id);
        if (Objects.nonNull(entity)) {
            if (entity.getActive().equals(1)){
                throw new IllegalArgumentException("表单为未激活状态，不允许修改数据");
            }
            entity.setStatus(status);
            return this.updateById(entity);
        }
        return false;
    }

    @Override
    public boolean rollbackFormDefinitionHistory(String formCode, Long version, Long rollbackFromOperator) {
        //todo 此处需要增加日志记录
        FormDefinition activeDbEntity = this.baseMapper.selectOne(new QueryWrapper<FormDefinition>().lambda().eq(FormDefinition::getFormCode, formCode).eq(FormDefinition::getActive, 0));
        if (Objects.isNull(activeDbEntity)) {
            throw new IllegalArgumentException("表单不存在");
        }
        if (!activeDbEntity.getStatus().equals(0)) {
            throw new IllegalArgumentException("表单为停用状态，不允许修改数据");
        }
        activeDbEntity.setActive(1);
        if (activeDbEntity.getVersion().equals(activeDbEntity.getMaxVersion())){
            activeDbEntity.setStatus(0);
        }else {
            activeDbEntity.setStatus(2);
        }
        this.updateById(activeDbEntity);
        //回退的目标版本
        FormDefinition target = this.baseMapper.selectOne(new QueryWrapper<FormDefinition>().lambda().eq(FormDefinition::getFormCode, formCode).eq(FormDefinition::getVersion, version), true);
        target.setActive(0);
        target.setStatus(0);
       return this.updateById(target);
    }


    /**
     * 处理数字序列
     *
     * @param currentSequence 当前数字序列
     * @param newNumber       新的数字
     * @return 处理后的数字序列
     */
    private String handleNumberSequence(String currentSequence, int newNumber) {
        if (currentSequence == null || currentSequence.isEmpty()) {
            return String.valueOf(newNumber);
        }

        String[] numbers = currentSequence.split(",");
        List<String> numberList = new ArrayList<>(Arrays.asList(numbers));
        numberList.add(String.valueOf(newNumber));

        // 优化后的截取逻辑
        if (numberList.size() > 10) {
            numberList = numberList.subList(numberList.size() - 10, numberList.size());
        }

        return String.join(",", numberList);
    }


}
